<template>
  <view class="login-container">
    <!-- 背景图 -->
    <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/6a164d38f01d49e6af11f0d5e4eba5fb.svg"
      mode="aspectFill" class="login-bg" />

    <!-- Logo和标题区域 -->
    <view class="header">
      <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png"
        class="logo" />
      <text class="title">博阳荟</text>
      <text class="subtitle">记录家族历史，传承家族文化</text>
    </view>

    <!-- 登录表单区域 -->
    <view class="login-card">
      <view class="form-wrap">
        <wd-form ref="loginFormRef" :model="loginFormData">
          <!-- 用户名输入框 -->
          <view class="form-item">
            <wd-icon name="user" size="22" color="#165DFF" class="input-icon" />
            <input v-model="loginFormData.username" class="form-input" placeholder="请输入用户名" />
            <!-- <wd-icon
              v-if="loginFormData.username"
              name="close-fill"
              size="18"
              color="#9ca3af"
              class="clear-icon"
              @click="loginFormData.username = ''"
            /> -->
          </view>
          <view class="divider"></view>

          <!-- 密码输入框 -->
          <view class="form-item">
            <wd-icon name="lock-on" size="22" color="#165DFF" class="input-icon" />
            <input v-model="loginFormData.password" class="form-input" :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码" placeholder-style="color: #9ca3af; font-weight: normal;" />
            <!-- <wd-icon
              name="eye-close"
              size="18"
              color="#9ca3af"
              class="eye-icon"
              @click="showPassword = !showPassword"
            /> -->
          </view>
          <view class="divider"></view>

          <!-- 记住密码选项 -->
          <view class="remember-password">
            <wd-checkbox v-model="rememberPassword" shape="circle" size="16">
              <text class="remember-text">记住密码</text>
            </wd-checkbox>
          </view>

          <!-- 登录按钮 -->
          <button class="login-btn" :disabled="loading" :style="loading ? 'opacity: 0.7;' : ''" @click="handleLogin">
            登录
          </button>

          <!-- 注册链接 -->
          <view class="register-link">
            <text class="register-text">未找到账号？</text>
            <text class="register-btn-text" @click="handleRegister">去注册</text>
          </view>
        </wd-form>

        <!-- 微信登录 -->
        <view class="other-login">
          <view class="other-login-title">
            <view class="line"></view>
            <text class="text">其他登录方式</text>
            <view class="line"></view>
          </view>

          <view class="wechat-login" @click="handleWechatLogin">
            <view class="wechat-icon-wrapper">
              <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/06670202e59e4de8b666b0ac747a73ca.png"
              class="wechat-icon" />
            </view>
          </view>
          <!-- <button class="login-btn wechat-login-btn" @click="handleWechatLogin" withCredentials="true">
            <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/06670202e59e4de8b666b0ac747a73ca.png"
              class="wechat-icon" />
            <text class="wechat-login-text">微信登录</text>
          </button> -->
        </view>

        <!-- 底部协议 -->
        <view class="agreement">
          <wd-checkbox v-model="agreementChecked" shape="circle" size="16">
            <text class="text">已阅读并同意</text>
            <text class="link" @click="navigateToUserAgreement">《用户协议》</text>
            <text class="text">和</text>
            <text class="link" @click="navigateToPrivacy">《隐私政策》</text>
          </wd-checkbox>
        </view>
      </view>
    </view>

    <wd-toast />
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app";
import { type LoginFormData } from "@/api/auth";
import AuthAPI from "@/api/auth";
import { useUserStore } from "@/store/modules/user";
import { useToast } from "wot-design-uni";
import { ref } from "vue";
import {
  getRememberPassword,
  setRememberPassword,
  getSavedUsername,
  getSavedPassword,
  saveLoginInfo,
  clearSavedLoginInfo,
} from "@/utils/cache";

const loginFormRef = ref();
const toast = useToast();
const loading = ref(false);
const userStore = useUserStore();

// 登录表单数据
const loginFormData = ref<LoginFormData>({
  username: "",
  password: "",
});

// 记住密码状态
const rememberPassword = ref(false);

// 密码显示状态
const showPassword = ref(false);

// 协议同意状态
const agreementChecked = ref(false);

// 获取重定向参数
const redirect = ref("");
onLoad((options) => {
  if (options.userId) {
    uni.navigateTo({
      url: '/pages/login/register?userId=' + options.userId
    });
  } else {
    redirect.value = "/pages/index/index";
  }
  console.log("userId", options.userId);
  // 加载保存的登录信息
  loadSavedLoginInfo();
});

// 加载保存的登录信息
const loadSavedLoginInfo = () => {
  const savedRememberPassword = getRememberPassword();
  rememberPassword.value = savedRememberPassword;

  if (savedRememberPassword) {
    const savedUsername = getSavedUsername();
    const savedPassword = getSavedPassword();
    if (savedUsername && savedPassword) {
      loginFormData.value.username = savedUsername;
      loginFormData.value.password = savedPassword;
    }
  }
};

// 登录处理
const handleLogin = () => {
  if (loading.value) return;
  // 检查用户是否同意协议
  if (!agreementChecked.value) {
    toast.warning('请先阅读并同意用户协议和隐私政策');
    return;
  }
  loading.value = true;

  userStore
    .login(loginFormData.value)
    .then(() => userStore.getInfo())
    .then(() => {
      toast.success("登录成功");

      // 处理记住密码
      if (rememberPassword.value) {
        setRememberPassword(true);
        saveLoginInfo(loginFormData.value.username, loginFormData.value.password);
      } else {
        setRememberPassword(false);
        clearSavedLoginInfo();
      }

      // 统一处理登录成功后的逻辑
      handleLoginSuccess();
    })
    .catch((error) => {
      console.error("登录失败:", error);
      toast.error(error?.message || "登录失败，请检查用户名和密码");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 注册处理
const handleRegister = () => {
  uni.navigateTo({
    url: "/pages/login/register",
  });
};

// 微信开放平台配置 - 请替换为您自己的appid
const WECHAT_CONFIG = {
  appid: 'wx95eef877b08f5f7e',
  redirectUri: encodeURIComponent('http://192.168.0.189:222/'),
  scope: 'snsapi_base', // 基础权限，仅获取openid
  state: 'STATE'
};

// 微信登录处理 - 跳转到微信授权页面
const handleWechatLogin = () => {
  // 检查用户是否同意协议
  if (!agreementChecked.value) {
    toast.warning('请先阅读并同意用户协议和隐私政策');
    return;
  }
  
  // 跳转到微信授权登录页面
  uni.navigateTo({
    url: '/pages/login/wechat-authorize'
  });
};
// if (loading.value) return;
// loading.value = true;

// // 检查用户是否同意协议
// if (!agreementChecked.value) {
//   toast.warning('请先阅读并同意用户协议和隐私政策');
//   loading.value = false;
//   return;
// }

// // 检查用户是否授权（在用户点击按钮时）
// if (userInfoRes && !userInfoRes.detail.userInfo) {
//   toast.warning('需要您的授权才能继续登录');
//   loading.value = false;
//   return;
// }

// // #ifdef MP-WEIXIN
// // 微信小程序环境：调用微信登录接口，这会触发微信登录授权页面
// uni.login({
//   provider: "weixin",
//   onlyAuthorize: true, // 仅请求授权认证，这会显示微信登录页面
//   success: async (res) => {
//     try {
//       if (res.code) {
//         console.log('获取微信登录code成功:', res.code);

//         // 这里可以调用后端接口进行登录认证
//         // 由于这是示例代码，我们暂时只打印code并显示成功提示
//         toast.success('获取微信授权成功');

//         // 在实际应用中，您应该调用真实的后端API
//         // const result = await userStore.loginByWechat(res.code);
//         // if (result) {
//         //   await userStore.getInfo();
//         //   handleLoginSuccess();
//         // }
//       } else {
//         throw new Error('获取微信登录code失败: ' + (res.errMsg || '未知错误'));
//       }
//     } catch (error: any) {
//       console.error("微信登录处理失败:", error);
//       toast.error(error?.message || "微信登录失败，请重试");
//     } finally {
//       loading.value = false;
//     }
//   },
//   fail: (err) => {
//     console.error("uni.login失败:", err);
//     toast.error("微信登录失败，请重试");
//     loading.value = false;
//   }
// });
// // #endif

// // #ifndef MP-WEIXIN
// // H5环境或其他环境提示
// toast.info("请在微信环境下使用微信登录");
// loading.value = false;
//   // #endif
// };

// 统一处理登录成功后的逻辑
const handleLoginSuccess = () => {
  // 检查用户信息是否完整
  if (!userStore.isUserInfoComplete()) {
    // 如果信息不完整，跳转到完善信息页面
    setTimeout(() => {
      uni.navigateTo({
        url: `/pages/login/complete-profile?redirect=${encodeURIComponent(redirect.value)}`,
      });
    }, 1000);
  } else {
    // 否则直接跳转到重定向页面
    setTimeout(() => {
      uni.reLaunch({
        url: redirect.value,
      });
    }, 1000);
  }
};

// 跳转到用户协议页面
const navigateToUserAgreement = () => {
  uni.navigateTo({
    url: "/pages/login/protectPrivacy/userAgreement",
  });
};

// 跳转到隐私政策页面
const navigateToPrivacy = () => {
  uni.navigateTo({
    url: "/pages/login/protectPrivacy/privacy",
  });
};
</script>

<style lang="scss" scoped>
.login-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  overflow: hidden;
}

.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.header {
  z-index: 2;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 120rpx;
}

.logo {
  width: 140rpx;
  height: 140rpx;
  margin-bottom: 20rpx;
}

.title {
  margin-bottom: 10rpx;
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.subtitle {
  font-size: 28rpx;
  color: #ffffff;
  text-align: center;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.login-card {
  z-index: 2;
  display: flex;
  flex-direction: column;
  width: 90%;
  margin-top: 80rpx;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.1);
}

.form-wrap {
  padding: 40rpx;
}

.form-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 24rpx 0;
}

.input-icon {
  margin-right: 20rpx;
}

.form-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  line-height: 60rpx;
  color: #333;
}

.clear-icon,
.eye-icon {
  padding: 10rpx;
}

.divider {
  height: 1px;
  margin: 0;
  background-color: rgba(0, 0, 0, 0.06);
}

.remember-password {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 40rpx;
  padding: 0 10rpx;
}

.remember-text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  margin-top: 60rpx;
  font-size: 32rpx;
  line-height: 90rpx;
  color: #fff;
  background: linear-gradient(90deg, #165dff, #4080ff);
  border: none;
  border-radius: 45rpx;
  box-shadow: 0 8rpx 20rpx rgba(22, 93, 255, 0.3);
  transition: all 0.3s;
}

.login-btn:active {
  box-shadow: 0 4rpx 10rpx rgba(22, 93, 255, 0.2);
  transform: translateY(2rpx);
}

.register-link {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
  font-size: 28rpx;
}

.register-text {
  color: #9ca3af;
}

.register-btn-text {
  color: #165dff;
  text-decoration: underline;
}

.other-login {
  margin-top: 60rpx;
}

.other-login-title {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.line {
  flex: 1;
  height: 1px;
  background-color: rgba(0, 0, 0, 0.08);
}

.text {
  padding: 0 30rpx;
  font-size: 26rpx;
  color: #9ca3af;
}

.wechat-login {
  display: flex;
  justify-content: center;
  margin-bottom: 30rpx;
}

.wechat-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 90rpx;
  height: 90rpx;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.wechat-icon {
  width: 60rpx;
  height: 60rpx;
}

.wechat-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #07C160;
  box-shadow: 0 8rpx 20rpx rgba(7, 193, 96, 0.3);
}

.wechat-login-btn:active {
  box-shadow: 0 4rpx 10rpx rgba(7, 193, 96, 0.2);
  transform: translateY(2rpx);
}

.wechat-login-text {
  margin-left: 10rpx;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
}

.agreement {
  display: flex;
  justify-content: center;
  margin-top: 30rpx;
  font-size: 24rpx;
}

.agreement .text {
  padding: 0 4rpx;
  color: #9ca3af;
}

.agreement .link {
  color: #165dff;
}
</style>
